﻿using Acme.BookStore.GoodTable;
using HIS;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace Acme.BookStore.Goodss
{
    
    [ApiExplorerSettings(GroupName = "v1")]
    public class GoodsServices : ApplicationService, IGoodsServices
    {
        private readonly IHttpContextAccessor _httpContextAccessor;

        private readonly IWebHostEnvironment _environment;
        public GoodsServices(IRepository<Goods> RoomCodeInfoRepository,IWebHostEnvironment environment, IHttpContextAccessor httpContextAccessor)
        {
            this.RoomCodeInfoRepository = RoomCodeInfoRepository;
            _environment = environment;
            _httpContextAccessor = httpContextAccessor;
        }

        public IRepository<Goods> RoomCodeInfoRepository { get; }

        /// <summary>
        /// 商品添加
        /// </summary>
        /// <param name="roomCodeInfoeDTO"></param>
        /// <returns></returns>
        [HttpPost("api/Goods")]
        public async Task<APIResult> GoodsAdd(GoodsCodeDTO roomCodeInfoeDTO)
        {
            try
            {
                Goods roomCodeInfo = ObjectMapper.Map<GoodsCodeDTO, Goods>(roomCodeInfoeDTO);
                await RoomCodeInfoRepository.InsertAsync(roomCodeInfo);
                if (roomCodeInfo == null)
                {
                    return new APIResult()
                    {
                        Code = CodeEnum.error,
                        Message = "添加失败"
                    };
                }
                return new APIResult()
                {
                    Code = CodeEnum.success,
                    Message = "商品添加成功"
                };
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 删除商品
        /// </summary>
        /// <param name="Ids"></param>
        /// <returns></returns>
        [HttpDelete("api/GoodsInfo")]
        public async Task<APIResult> GoodsInfoDelete(string Ids)
        {
            try
            {
                var idList = Ids.Split(',').Select(x => Convert.ToInt32(x)).ToList();
                var roomTypes = await RoomCodeInfoRepository.GetListAsync(x => idList.Contains(x.Id));

                if (roomTypes == null || !roomTypes.Any())
                {
                    return new APIResult()
                    {
                        Code = CodeEnum.error,
                        Message = "删除失败，未找到指定的商品"
                    };
                }

                foreach (var roomType in roomTypes)
                {
                    await RoomCodeInfoRepository.DeleteAsync(roomType);
                }

                return new APIResult()
                {
                    Code = CodeEnum.success,
                    Message = "删除成功"
                };
            }
            catch (Exception ex)
            {
                return new APIResult()
                {
                    Code = CodeEnum.error,
                    Message = $"删除失败: {ex.Message}"
                };
            }
        }

        /// <summary>
        /// 商品信息展示
        /// </summary>
        /// <param name="GoodsName"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpGet("api/GoodsInfo")]
        public async Task<APIResult<List<GoodsCodeDTO>>> GoodsInfoShow(string GoodsName)
        {

            try
            {
                var list = await RoomCodeInfoRepository.GetListAsync(x => x.IsDeleted == false);
                if (GoodsName != null)
                {
                    list = list.Where(x => x.GoodsName == GoodsName).ToList();
                }
                return new APIResult<List<GoodsCodeDTO>>()
                {
                    Code = CodeEnum.success,
                    Message = "查询成功",
                    Data = ObjectMapper.Map<List<Goods>, List<GoodsCodeDTO>>(list.ToList())
                };
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 商品更新
        /// </summary>
        /// <param name="roomCodeInfoUpdateDTO"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpPost("api/GoodsUpdate")]
        public async Task<APIResult> GoodsUpdate(GoodsServicesUpdateDTO roomCodeInfoUpdateDTO)
        {
            try
            {
                var roomType = await RoomCodeInfoRepository.FirstOrDefaultAsync(x => x.Id == roomCodeInfoUpdateDTO.Id);
                if (roomType == null)
                {
                    return new APIResult()
                    {
                        Code = CodeEnum.error,
                        Message = "商品未找到"
                    };
                }

                ObjectMapper.Map(roomCodeInfoUpdateDTO, roomType);
                await RoomCodeInfoRepository.UpdateAsync(roomType);

                return new APIResult()
                {
                    Code = CodeEnum.success,
                    Message = "商品修改成功"
                };
            }
            catch (Exception ex)
            {
                return new APIResult()
                {
                    Code = CodeEnum.error,
                    Message = $"修改失败: {ex.Message}"
                };
            }
        }

        /// <summary>
        /// 删除单个商品
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpDelete("api/GoodsInfoSingleDelete")]
        public async Task<APIResult> GoodsInfoSingleDelete(int Id)
        {
            try
            {
                var roomcode = await RoomCodeInfoRepository.FirstOrDefaultAsync(x => x.Id == Id);
                if (roomcode == null)
                {
                    return new APIResult()
                    {
                        Code = CodeEnum.error,
                        Message = "删除失败，未找到指定的商品"
                    };
                }
                await RoomCodeInfoRepository.DeleteAsync(roomcode);
                return new APIResult()
                {
                    Code = CodeEnum.success,
                    Message = "删除成功"
                };
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 修改商品列表状态
        /// </summary>
        /// <param name="Ids"></param>
        /// <returns></returns>
        [HttpPut("api/GoodTypeUpdateStatus")]
        public async Task<APIResult> GoodsUpdateStatus(string Ids)
        {
            try
            {
                var idList = Ids.Split(',').Select(x => Convert.ToInt32(x)).ToList();
                var roomTypes = await RoomCodeInfoRepository.GetListAsync(x => idList.Contains(x.Id));

                if (roomTypes == null || !roomTypes.Any())
                {
                    return new APIResult()
                    {
                        Code = CodeEnum.error,
                        Message = "修改失败，未找到指定的商品"
                    };
                }

                foreach (var roomType in roomTypes)
                {
                    roomType.GoodsState = false;
                    await RoomCodeInfoRepository.UpdateAsync(roomType);
                }

                return new APIResult()
                {
                    Code = CodeEnum.success,
                    Message = "修改成功"
                };
            }
            catch (Exception ex)
            {
                return new APIResult()
                {
                    Code = CodeEnum.error,
                    Message = $"修改失败: {ex.Message}"
                };
            }
        }

        /// <summary>
        /// 上传商品类型图片
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost("api/Goods/UploadImage")]
        public async Task<APIResult<string>> UploadGoodsTypeImage(IFormFile file)
        {
            if (file == null || file.Length == 0)
            {
                return new APIResult<string>()
                {
                    Code = CodeEnum.error,
                    Message = "文件为空",
                    Data = null
                };
            }

            var uploadsFolder = Path.Combine(_environment.WebRootPath, "images");
            if (!Directory.Exists(uploadsFolder))
            {
                Directory.CreateDirectory(uploadsFolder);
            }

            var filePath = Path.Combine(uploadsFolder, file.FileName);
            var relativePath = Path.Combine("images", file.FileName);

            try
            {
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }
                var Request = _httpContextAccessor.HttpContext?.Request;
                var imageUrl = $"{Request.Scheme}://{Request.Host}/{relativePath.Replace("\\", "/")}";

                return new APIResult<string>()
                {
                    Code = CodeEnum.success,
                    Message = "图片上传成功",
                    Data = imageUrl
                };
            }
            catch (Exception ex)
            {
                return new APIResult<string>()
                {
                    Code = CodeEnum.error,
                    Message = $"图片上传失败: {ex.Message}",
                    Data = null
                };
            }
        }
    }
}
